#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>

void show_return_status(void)
{
	pid_t childpid;
	int status;

	childpid = wait(&status);
	if (childpid == -1) {
		perror("Failed to wait for the child process");
	} else if (WIFEXITED(status) && !WEXITSTATUS(status)) {
		printf("Child %d exited normally\n", childpid);
	} else if (WIFEXITED(status)) {
		printf("Child %d exited with the status %d\n", childpid, \
				WEXITSTATUS(status));
	} else if (WIFSIGNALED(status)) {
		printf("child %d exited due to uncaught signal %d\n", childpid, \
				WTERMSIG(status));
	} else if (WIFSTOPPED(status)) {
		printf("child %d stoped due to the signal %d\n", childpid, \
				WSTOPSIG(status));
	}
}

int main(int argc, char **argv)
{
	pid_t childpid = 0;
	int i, n;

	if (argc != 2) {
		fprintf(stderr, "Usage: %s processes\n", argv[0]);
		return 1;
	}

	n = atoi(argv[1]);
	for (i = 1; i < n; i++) {
		if ((childpid = fork()) <= 0)
			break;
		show_return_status();
	}
	
	fprintf(stderr, "i:%d process ID: %ld parent ID:%ld child ID: %ld\n", i, 
			(long)getpid(), (long)getppid(), (long)childpid);
	exit(0);
}
